﻿<?PHP
require_once("base.wpfb.php");
require_once ('src/facebook.php');

class ImportFacebookStatus extends WpEnvironemt{

private $parentPage = null;
private $StatusInsertPage = null;
private $globalVars = null;

public function __construct($parentPage, $StatusInsertPage)
{
	$this->globalVars = new WPFB($parentPage);
	$this->parentPage = $parentPage;
	$this->StatusInsertPage = $StatusInsertPage;
}

protected function initAllVariables() {}

public function processStatus()
{
	if( isset($_GET['post']) )
		$this->processStatusasNewWordpressPost();
	else	
		$this->processStatusasNewWordpressPost_UI();
}
private function processStatusasNewWordpressPost()
{
	try{
		global $current_user;
		get_currentuserinfo();

		if( isset($_POST['title']) || isset($_POST['content']))
		{
			//throw new Exception('Some parameter(s) is missing');
			if( isset($_POST['tags_input']) )
				$tags_input = explode(';', $_POST['tags_input']);
			else if (isset($_POST['link']))
				$tags_input = parse_url($_POST['link'], PHP_URL_HOST);
			else
				$tags_input = array('Imported via Status');

			$my_post = array(
				'post_title' => $_POST['title'],
				'post_content' => $_POST['content'],
				'post_status' => 'pending',
				'post_author' => $current_user->ID,
				'tags_input' => $tags_input
			);
			
			$post_id = wp_insert_post( $my_post, true );
			if( is_wp_error($post_id) )
			{ 
				throw new Exception($post_id->get_error_message());
			}
			echo "Successfully queued and having pending status: ". get_bloginfo('siteurl'). '/?p='. $post_id;
		}
		else
			throw new Exception('Somehow post title or post content were not sent to server. Please try again.');
	}catch(Exception $e)
	{
		$this->printException($e);
	}
	exit(); //This was an ajax request.
}

private function processStatusasNewWordpressPost_UI()
{
?>
<h1> Import FacebookStatus as a Wordpress post </h1>
Insert Status id:
<input type="text" value="" size="50" maxlength="1000" id="my_Status" noBanglaText='noBanglaText' onclick='select();' />
<button class="click" ID="importStatus">Import</button>
<br/><small>Only public Statuss can be imported</small>

<div  style='width:600px;'>
<br/><br/><br/><span style='color:red'></span><br/>
<table id="data_table" border="1">
<thead>
<tr>
<th>Serial</th>
<th>Title of the post</th>
<th>Import link</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>

<script type='text/javascript' src='//cdn.datatables.net/1.10.0/js/jquery.dataTables.js'></script>
<style type="text/css">@import url("//cdn.datatables.net/1.10.0/css/jquery.dataTables.css");</style>
<style type="text/css">td { max-width: 100px; }</style>
<script type="text/javascript">

(function($){
$('#data_table').dataTable({'aaSorting': [[ 0, 'desc' ]]} );

$("#importStatus").click(function(){
	var access_token = "<?PHP echo $this->globalVars->facebook->getAccessToken(); ?>";
	var url=$("#my_Status").val();
	
	if(isNaN(parseFloat(url)) || !isFinite(url))
	{
		//It's not numeric
		alert("Status id must be numeric");
		return;
	}
	
	var json = $.getJSON("https://graph.facebook.com/v2.1/"+url+"?callback=?&access_token="+access_token+"&id="+url+"&fields=location,name,start_time,invited_count,description,owner,cover",
	function(data)
	{
		// importedData = a global variable; not good
		if( data.error != null)
		{
			alert("Error: " + data.error.message);
			return;
		}
		importedData = data;
		
		importedData.title = data.name;
		var coverPicture = !!data.cover ? "<img src='"+data.cover.source+"'/>" : "";
		
		importedData.content = coverPicture;
		importedData.content += !!data.description ? data.description : '';
		importedData.content += "<br/><strong>সময়:</strong> "+data.start_time;
		importedData.content += !!data.location? "<br/><strong>স্থান:</strong> <iframe width='100%' height='450' frameborder='0' style='border:0' src='https://www.google.com/maps/embed/v1/place?q="+data.location+"&key=AIzaSyD6adqXx63f1XiWcq12IR3dQ6tvdyD4vvg'></iframe>" : '';
		importedData.content += "<br/><strong>আয়োজক:</strong> "+data.owner.name; 

		importedData.link = "https://www.facebook.com/Statuss/"+url;
		importedData.content += "<br/><strong>বিস্তারিত:</strong> <a href='"+importedData.link+"' target='_blank'>"+importedData.link+"</a>";
		
		$('#data_table').dataTable().fnAddData([0, data.name, '<button onclick="insertPost(0)" style="font-style:bold" >Submit</button>']);
	});
	
	insertPost= function(i)
	{
		var data={
			title: importedData.title,
			content: importedData.content,
			link: importedData.link
		};
		
		$.post("<?PHP echo get_bloginfo('wpurl') . "/wp-admin/admin-ajax.php?action={$this->StatusInsertPage}&post=post2"; ?>", data,
		function(response)
		{
			//console.log(response);
			alert(response);
			$('#data_table').dataTable().fnDeleteRow(i);
		});
	}
});

//end of function
})(jQuery);
</script>

<br/><br/><br/><br/>

<?php 
}

} // class ends here
?>